package com.acme.bankapp.domain.bank;

import com.acme.bankapp.domain.bank.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;
import com.acme.bankapp.service.bank.EmailService;

import java.io.Serializable;
import java.util.*;

public class Bank implements Serializable {
    private static class DebugListener implements ClientRegistrationListener {
        @Override
        public void onClientAdded(Client client) {
            System.out.println(new Date() + "  " + client.getSalutation());
        }
    }

    public class EmailClientListener implements ClientRegistrationListener {
        private EmailService emailService;

        public EmailClientListener(EmailService emailService) {
            this.emailService = emailService;
        }

        @Override
        public void onClientAdded(Client client) {
            emailService.sendNotificationEmail(new Email(client));
        }

        @Override
        public void close() {
            emailService.close();
        }
    }

    private Set<Client> clients = new HashSet<>();
    private transient List<ClientRegistrationListener> listeners;
    private String bankPath;

    public Bank() {
        initListeners();
    }

    public void setBankPath(String bankPath) {
        this.bankPath = bankPath;
    }

    public void stopListeners() {
        for (ClientRegistrationListener listener : listeners) {
            listener.close();
        }
    }

    public String getBankPath() {
        return bankPath;
    }

    public Client[] getClients() {
        return clients.toArray(new Client[clients.size()]);
    }

    public void initListeners() {
        listeners = new LinkedList<>();
        addListener(new DebugListener());
    }

    public void addListener(ClientRegistrationListener clientRegistrationListener) {
        listeners.add(clientRegistrationListener);
    }

    public Client addClient(Client client) throws ClientExistsException {
        if (!clients.add(client)) {
            throw new ClientExistsException("Client with name " + client.getName() + "already exists in bank");
        }

        for (ClientRegistrationListener listener : listeners) {
            listener.onClientAdded(client);
        }

        return client;
    }
}
